<template>
  <div class="all">
    <div class="top">
      <header>
        <div class="div">
          <img src="../../../assets/返回.png" @click="back()" alt="">
          <span class="solid" @click="back()">返回</span>
        </div>
        <div class="div">
          <span>{{typeTitle}}</span>
<!--          <span v-show="type == 1">图文咨询</span>-->
<!--          <span v-show="type == 2">视频咨询</span>-->
        </div>
        <div class="div">
          <span class="solid"></span>
        </div>
      </header>
      <div class="menu">
        <el-steps :active="menuIndex" align-center>
          <el-step title=""
                   v-for="(item, index) in (type== 5 ? menuList5 : menuList)"
                   :key="index"
                   @click.native="changeMenu(index)"
                   process-status="success"
                   :description="item.title">
            <template #icon>
              <div v-if="menuIndex >= index" style="width: 15px;height: 15px;">
                <img src="../../../assets/步骤选择.png" style="width: 15px;height: 15px;" alt="">
              </div>
              <div v-else style="width: 6px;height: 15px;background: #1DA4F2;display: flex;align-items: center;justify-content: center">
                <a style="width: 6px;height: 6px;border-radius: 50%;background: white;display: flex;position: absolute;"></a>
              </div>
            </template>
          </el-step>
        </el-steps>
      </div>
    </div>
    <div class="time">
      <p>
        请在 <span> {{minute}}分{{second}}秒</span>内完成支付，超时订单自动取消
      </p>
    </div>
    <div class="xiangMu label" style="height: 35px;">
      项目：{{typeTitle}}
      {{order.doc_amount_name ? order.doc_amount_name : DATA.doc_amount_name ? DATA.doc_amount_name : ''}}
      {{doctorName}}
    </div>
    <div class="label" style="height: 35px;margin-bottom: 5px">
      价格：<span class="price">￥{{price}}</span>
    </div>
    <div class=" label" style="font-weight: bold">
      <a class="hengGang"></a>支付方式
    </div>
    <div class="label pay">
     <span>
        <img class="weixin" src="../../../assets/微信支付.png" alt="">
      微信
     </span>
      <img class="selectImg" src="../../../assets/题目选择.png" alt="">
    </div>
<!--    <button class="payBtn" @click.once="getApi()">确认支付</button>-->

    <div class="bottom">
      <div class="bottomDiv">实际支付 <span class="price">￥{{price}}</span></div>
      <div @click="getApi()" class="bottomDiv payBtn">立即支付</div>
    </div>
  </div>
</template>

<script>
import {Toast} from 'vant'
export default {
  name: 'TuWenThirdAdd',
  data () {
    return {
      menuList: [
        {
          title: '选择医生/团队',
          url: '/first'
        },
        {
          title: '预约信息',
          url: '/tuWenPrice'
        },
        {
          title: '咨询准备',
          url: '/second'
        },
        {
          title: '费用支付',
          url: '/third'
        }
      ],
      menuList5: [
        {
          title: '选择医生/团队',
          url: '/first'
        },
        {
          title: '预约信息',
          url: '/tuWenPrice'
        },
        {
          title: '会诊准备',
          url: '/second'
        },
        {
          title: '费用支付',
          url: '/third'
        }
      ],
      price: '',
      doctorName: '',
      time: 0,
      type: Number(this.$route.query.type),
      minutes: 30,
      seconds: 0,
      detail: Number(this.$route.query.detail),
      timeInster: '',
      Inquirying: false,
      isSendPay: true,
      order: [],
      DATA: []
    }
  },
  mounted () {
    if (sessionStorage.getItem('order')) {
      var orderItem = JSON.parse(sessionStorage.getItem('order'))
      this.order = JSON.parse(sessionStorage.getItem('order'))
      if (orderItem.type) {
        this.type = orderItem.type
      }
      this.price = orderItem.amount
      this.doctorName = orderItem.name
      var nowTime = new Date(orderItem.created_at)
      if (orderItem.created_at !== 'NaN' && orderItem.created_at !== undefined && orderItem.created_at !== null) {
        let jianTime = 30 * 60 * 1000 - new Date(new Date() - nowTime)
        if (jianTime <= 0) {
          jianTime = 0
        }
        this.time = new Date(jianTime)
        this.minutes = this.time.getUTCMinutes()
        this.seconds = this.time.getUTCSeconds()
      }
    }
    if (sessionStorage.getItem('DATA') !== null) {
      var data = JSON.parse(sessionStorage.getItem('DATA'))
      this.DATA = JSON.parse(sessionStorage.getItem('DATA'))
    }
    if (sessionStorage.getItem('FirstData') !== null) {
      var doctor = JSON.parse(sessionStorage.getItem('FirstData'))
      this.doctorName = doctor.name
      // 新建进入
      this.price = data.amount
    }
    this.timer()

    this.getFindInquiryingList()
  },
  methods: {
    // 医生端 图文退诊
    jujueConfirm () {
      if (this.cancel_reason === '') {
        Toast('请填写退诊原因')
        this.juZhenShow = true
        return false
      } else {
        this.$http.doctorNoJieZhen({id: this.ITEM.id, cancel_reason: this.cancel_reason})
          .then(res => {
            console.log(res)
            if (res.data.status === 'success') {
              Toast('退诊成功')
              this.getTuWenData()
              this.cancel_reason = ''
              this.juZhenShow = false
            }
          })
          .catch(err => {
            console.log(err)
          })
      }
    },
    // 医生端 图文退诊
    juZhen (item) {
      this.ITEM = item
      this.juZhenShow = true
      // cancel_reason 拒绝诊断理由
    },
    // 查看与该医生是否有 进行中的订单
    getFindInquiryingList () {
      // miniinqs/findInquiryingList
      // 查看与医生是否有进行中的咨询订单
      // 您与该医生已存在未结束的订单，无法支付
      let data = JSON.parse(sessionStorage.getItem('DATA'))
      let order = JSON.parse(sessionStorage.getItem('order'))
      let docUserid
      if (data !== null && data.doc_user_id !== null && data.doc_user_id !== '' && data.doc_user_id !== undefined) {
        docUserid = data.doc_user_id
      } else if (order.doc_user_id !== null && order.doc_user_id !== '' && order.doc_user_id !== undefined) {
        docUserid = order.doc_user_id
      }
      this.$http.findInquiryingList({doc_user_id: docUserid, type: this.type})
        .then(res => {
          console.log(res.data)
          if (res.data.status === 'success') {
            if (res.data.data.length <= 0) {
              this.Inquirying = false // 没有进行中 可以支付
            } else {
              this.Inquirying = true // 有进行中 不能支付
            }
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    num (n) {
      return n < 10 ? '0' + n : '' + n
    },
    timer () {
      var _this = this
      this.timeInster = window.setInterval(function () {
        if (_this.seconds === 0 && _this.minutes !== 0) {
          _this.seconds = 59
          _this.minutes -= 1
        } else if (_this.minutes <= 0 && _this.seconds <= 0) {
          _this.seconds = 0
          window.clearInterval(_this.timeInster)
          _this.back()
        } else {
          _this.seconds -= 1
        }
      }, 1000)
    },
    // 返回
    back () {
      // this.$router.push({path: '/tuWenHome', query: {'type': this.type}})
      // this.$router.history.go(-1)
      var index
      if (sessionStorage.getItem('FirstData') !== null) {
        index = this.backIndex
      } else if (this.detail == 1) {
        index = 2
      } else {
        index = 1
      }
      this.$router.history.go(-Number(index))
    },
    changeMenu (index) {
      Toast('请完成支付再离开此页面')
    },
    getApi () {
      // 没有进行中 可以支付
      if (this.Inquirying === false) {
        if (this.isSendPay === true) {
          this.isSendPay = false
          var data = JSON.parse(sessionStorage.getItem('order'))
          if (sessionStorage.getItem('sys') === 'ANDROID') {
            let index
            if (sessionStorage.getItem('FirstData') !== null) {
              let aa = Number(this.backIndex)
              index = aa
            } else if (this.detail == 1) {
              index = 2
            } else {
              index = 1
            }
            window.WebViewJavascriptBridge.callHandler('wxPayForDoctor', data.order_no + ',' + data.amount + ',' + index, function (responseData) {})
          } else {
            this.$http.pay({order_no: data.order_no, amount: data.amount})
              .then(res => {
                console.log(res)
                if (res.data.status === 'success') {
                  window.WeixinJSBridge.invoke(
                    'getBrandWCPayRequest', {
                      'appId': res.data.data.appId, // 公众号名称，由商户传入
                      'timeStamp': res.data.data.timestamp, // 时间戳，自1970年以来的秒数
                      'nonceStr': res.data.data.nonceStr, // 随机串
                      'package': res.data.data.packageValue,
                      'signType': res.data.data.signType, // 微信签名方式：
                      'paySign': res.data.data.paySign // 微信签名
                    },
                    function (res) {
                      if (res.err_msg === 'get_brand_wcpay_request:ok') {
                      // 使用以上方式判断前端返回,微信团队郑重提示：
                      // res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
                        if (sessionStorage.getItem('FirstData') !== null) {
                          if (this.type !== 5) {
                            window.history.go(-4)
                          } else {
                            window.history.go(-5)
                          }
                        } else if (this.detail == 1) {
                          window.history.go(-2)
                        } else {
                          window.history.go(-1)
                        }
                        Toast('支付成功')

                        let sendMsg
                        let DATA
                        let userId
                        let nickname
                        let message
                        if (sessionStorage.getItem('FirstData') !== null) {
                          sendMsg = JSON.parse(sessionStorage.getItem('FirstData'))
                          DATA = JSON.parse(sessionStorage.getItem('DATA'))
                          userId = sendMsg.doctorUserID
                          nickname = sendMsg.name
                          message = DATA.illness_desc
                        } else {
                          sendMsg = JSON.parse(sessionStorage.getItem('order'))
                          userId = sendMsg.doc_user_id
                          nickname = sendMsg.STAFF_NAME
                          message = sendMsg.illness_desc
                        }
                        // 发送聊天提示语：  sendChatMessage
                        // 参数： userId（医生id） ，nickname（医生名称），message（要发送的内容 病情描述）
                        if (sessionStorage.getItem('sys') === 'ANDROID') {
                          window.WebViewJavascriptBridge.callHandler('sendChatMessage', userId + ',' + nickname + ',' + message, function (responseData) {})
                        }

                        // window.location.href = '../../../vue_kfhl/#/tuWenHome?type=' + data.type
                        sessionStorage.removeItem('DATA')
                        sessionStorage.removeItem('FirstData')
                        sessionStorage.removeItem('tuWenPeopleServedData')
                        sessionStorage.removeItem('SecondData')
                        sessionStorage.removeItem('order')
                        sessionStorage.removeItem('tuWenData')
                      } else {
                      // window.location.href = '../../../vue_kfhl/#/tuWenHome?type=' + data.type
                        if (sessionStorage.getItem('FirstData') !== null) {
                          if (this.type !== 5) {
                            window.history.go(-4)
                          } else {
                            window.history.go(-5)
                          }
                          // window.history.go(-this.backIndex)
                        } else if (this.detail == 1) {
                          window.history.go(-2)
                        } else {
                          window.history.go(-1)
                        }
                        Toast('支付失败')
                        sessionStorage.removeItem('DATA')
                        sessionStorage.removeItem('FirstData')
                        sessionStorage.removeItem('tuWenPeopleServedData')
                        sessionStorage.removeItem('SecondData')
                        sessionStorage.removeItem('order')
                        sessionStorage.removeItem('tuWenData')
                      }
                    })
                }
              })
              .catch(err => {
                console.log(err)
              })
          }
        } else {
          Toast('请不要重复点击')
        }
      } else if (this.Inquirying === true) {
        Toast('您与该医生已存在未结束的订单，无法支付')
      }
    }
  },
  computed: {
    typeTitle: function () {
      if (this.type === 1) {
        document.title = '图文咨询'
        return '图文咨询'
      } else if (this.type === 2) {
        document.title = '视频咨询'
        return '视频咨询'
      } else if (this.type === 5) {
        document.title = '远程会诊'
        return '远程会诊'
      }
    },
    menuIndex: function () {
      return 3
      // if (this.type !== 5 && this.type !== 2) {
      //   return 3
      // } else {
      //   return 4
      // }
    },
    second: function () {
      var num = this.num(this.seconds)
      if (num <= 0) {
        num = 0
      }
      return num
    },
    minute: function () {
      var num = this.num(this.minutes)
      if (num <= 0) {
        num = 0
      }
      return num
    },
    backIndex: function () {
      return 4
      // if (this.type !== 5 && this.type !== 2) {
      //   return 4
      // } else {
      //   return 5
      // }
    }
  },
  watch: {
    second: {
      handler (newVal) {
        this.num(newVal)
      }
    },

    minute: {
      handler (newVal) {
        this.num(newVal)
      }
    }

  }
}
</script>

<style scoped>
  .all{
    width: 100%;
    height: 100%;
    overflow: auto;
    background: #FAF9FE;
  }
  .top{
    position: sticky;
    top: 0;
    background: white;
  }
  header{
    width: 100%;
    height: 44px;
    display: flex;
    align-items: center;
    font-family: "PingFang SC";
  }
  .menu{
    width: 100%;
    height: 60px;
    background: #1DA4F2;
    box-shadow: 0px 1px 0px 0px #E5E5E5;
    display: flex;
    align-items: center;
    justify-content: center;
    overflow:hidden;
  }
  .div{
    width: 33%;
    font-size: 15px;
    font-weight: bold;
    display: flex;
    align-items: center;
  }
  .div:nth-child(1) img{
    width: 7px;
    height: 13px;
    margin: 0 5px 0 15px;
  }
  .div:nth-child(2){
    justify-content: center;
  }
  .div:nth-child(3){
    justify-content: flex-end;
  }
  .div:nth-child(3) span{
    margin-right: 15px;
  }
  .solid{
    color: #1DA4F2;
  }
  .time{
    width: 100%;
    height: 40px;
    display: flex;
    align-items: center;
    /*justify-content: center;*/
    font-size: 15px;
    font-family: PingFang SC;
    font-weight: 500;
    color: #333333;
    background: rgba(227, 23, 13, 0.1);
    padding: 0 10px;
    box-sizing: border-box;
  }
  .time span{
    color: #E3170D !important;
    font-size: 13px !important;
  }
  .label{
    width: 100%;
    height: 44px;
    display: flex;
    align-items: center;
    background: white;
    padding: 0 10px;
    box-sizing: border-box;
    font-size: 15px;
    font-family: PingFang SC;
    font-weight: 500;
    color: #333333;
  }
  .price {
    color: #E3170D !important;
  }
  .hengGang{
    display: block;
    width: 2px;
    border-radius: 1px;
    height: 15px;
    background: #1DA4F2;
    margin-right: 5px;
  }
  .weixin{
    width: 16px;
    height: 16px;
    margin-right: 8px;
  }
  .payBtn{
    width: 100%;
    height: 100%;
    background: linear-gradient(90deg, #1DA3F2 0%, #1DC7F2 100%);
    border: none;
    font-size: 17px !important;
    font-family: PingFang SC;
    font-weight: bold;
    color: #FFFFFF;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .pay{
    justify-content: space-between;
  }
  .selectImg{
    width: 16px;
    height: 16px;
  }
  .bottom{
    width: 100%;
    height: 50px;
    display: flex;
    align-items: center;
    background: #fff;
    position: fixed;
    bottom: 50px;
  }
  .bottomDiv{
    width: 50%;
    font-size: 17px;
    padding: 0 10px;
    box-sizing: border-box;
  }
  /*/ 选择框 开始样式/*/
  /deep/ .el-steps--horizontal{
    width: 105%;
  }
  /deep/ .el-step.is-center .el-step__description{
    padding: 0;
  }
  /deep/ .el-step__description{
    margin: 0;
    font-size: 13px;
  }
  /deep/ .el-step__icon{
    width: auto;
    height: auto;
  }
  /deep/ .el-step__icon.is-text{
    border: none;
  }
  /deep/ .is-finish,
  /deep/ .el-step__description.is-process{
    color: #fff;
  }
  /deep/ .el-step__description.is-finish{
    color: white !important;
  }
  /deep/ .el-step__description.is-wait{
    color: rgba(255, 255, 255, 0.7);
  }
  /deep/ .el-step__head.is-finish{
    border-color: #fff;
  }
  /deep/ .el-step__head.is-wait{
    border-color: transparent !important;
  }
  /deep/ .el-step__line{
    border-color: transparent !important;
  }
  /deep/ .el-step.is-horizontal .el-step__line{
    height: 1px;
    /*top:7px;*/
    top: 35%;
  }
  /deep/ .el-step__line{
    background: white;
  }
  /*/ 选择框 结束样式/*/
</style>
